package com.gzyj.video.server;


import com.gzyj.video.handler.rtp.Jtt1078Handler;
import com.gzyj.video.handler.rtp.Jtt1078MessageDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.util.concurrent.TimeUnit;

/**
 * @author lhj
 */
@Service
@Slf4j
public class NettyServer {
    private static ServerBootstrap serverBootstrap;

    private static EventLoopGroup bossGroup;
    private static EventLoopGroup workerGroup;

    @Value("${server.backlog}")
    private Integer backlog;

    @Value("${server.worker-count}")
    private Integer workerCount = Runtime.getRuntime().availableProcessors();

    @Value("${video.server.port}")
    private Integer videoServerPort;


    @Value("${http.server.port}")
    private int serverPort;

    @Value("${version}")
    private String version;

    public static byte[] DataFramePrefix = {0x30, 0x31, 0x63, 0x64};



    public void start() throws Exception {
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.option(ChannelOption.SO_BACKLOG, backlog);
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 600000)
                .childOption(NioChannelOption.SO_TIMEOUT, 60000)
                .option(ChannelOption.SO_BACKLOG, 2048)
                .childOption(ChannelOption.SO_KEEPALIVE,true)

                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline p = channel.pipeline();
                        p.addLast(new IdleStateHandler(3600, 3600, 3600, TimeUnit.SECONDS));

//                        ByteBuf delimiter = Unpooled.copiedBuffer(new byte[]{0x30,0x31,0x63,0x64});
//                        p.addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, false, delimiter));
                        //                        p.addLast(new Message2PackHandler());
                        p.addLast(new Jtt1078MessageDecoder(version));

                        p.addLast(new Jtt1078Handler(serverPort,version));
                    }
                });

       /* ChannelFuture cf = null;
        cf = serverBootstrap.bind(videoServerPort).sync();
        cf.channel().closeFuture().sync();*/
        Channel ch = serverBootstrap.bind(InetAddress.getByName("0.0.0.0"), videoServerPort).sync().channel();
        log.info("Video Server started at: {}", videoServerPort);
        ch.closeFuture();
    }

    private void shutdown() {
        try {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
